package com.ycsj.goldmedalnewconcept.teacher.activity;

import android.graphics.drawable.BitmapDrawable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.InputFilter;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.ycsj.common.base.BaseActivity;
import com.ycsj.common.base.BaseApplication;
import com.ycsj.common.base.BusInfo;
import com.ycsj.common.manager.BqaManager;
import com.ycsj.common.manager.CustomDialogManager;
import com.ycsj.common.manager.PopUpManager;
import com.ycsj.common.manager.SrfManager;
import com.ycsj.common.utils.GsonUtil;
import com.ycsj.common.utils.MaxTextLengthFilter;
import com.ycsj.common.utils.StateBarUtil;
import com.ycsj.common.utils.UiUtils;
import com.ycsj.goldmedalnewconcept.R;
import com.ycsj.goldmedalnewconcept.common.HttpAddress;
import com.ycsj.goldmedalnewconcept.common.bean.ResultInfo;
import com.ycsj.goldmedalnewconcept.common.http.HttpUtils;
import com.ycsj.goldmedalnewconcept.common.util.AccountUtils;
import com.ycsj.goldmedalnewconcept.teacher.adapter.ScortDetailsGvAapter;
import com.ycsj.goldmedalnewconcept.teacher.adapter.SortLvAdapter;
import com.ycsj.goldmedalnewconcept.teacher.bean.ScoreDetailsInfo;
import com.ycsj.goldmedalnewconcept.teacher.bean.SortInfo;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

/**
 * 成绩详情列表
 * Created by Administrator on 2018/6/28 0028.
 */
public class TeacherScoreDetailsActivity extends BaseActivity implements View.OnClickListener {

    private ImageView ivBack;
    //标题
    private TextView tvStTitle;
    private ImageView ivEdit;
    //排序
    private TextView tvSort;
    private LinearLayout llTitle;
    private RecyclerView rv;
    private SmartRefreshLayout srf;
    private RelativeLayout rlLoading;
    private RelativeLayout rlContent;
    //班级
    private String userClass;
    //标题
    private String title;
    //测试主题Id
    private String tagid;

    //适配器
    private ScortDetailsGvAapter adapter;

    //数据集合
    private List<ScoreDetailsInfo.DataBean> oldDatas;

    //用于克隆数据集合,方便做排序处理
    private List<ScoreDetailsInfo.DataBean> cloneDatas;

    //空视图
    private View emptyView;

    //排序的数据集合
    private List<SortInfo> sortInfos;

    //排序的Pop相关控件
    private ListView lv;
    private SortLvAdapter sortLvAdapter;
    private PopupWindow popupWindow;

    //接受事件的标识
    public static final int UPDATASCORE = 0X330;

    @Override
    protected int getContentLayout() {
        return R.layout.activity_teacher_score_details;
    }

    @Override
    protected void init() {

        //设置状态栏颜色
        StateBarUtil.customImmerseBar(this);

        //初始化视图
        initView();

        //初始化下拉刷新
        initSfr();

        //获取传递的数据
        initIntent();

        //设置列表
        initRv();

        //请求数据
        http(BqaManager.NORML);
    }


    /**
     * 初始化视图
     */
    public void initView() {
        ivBack = findViewById(R.id.iv_back);
        ivBack.setOnClickListener(this);
        tvStTitle = findViewById(R.id.tv_title);
        ivEdit = findViewById(R.id.iv_edit);
        ivEdit.setOnClickListener(this);
        tvSort = findViewById(R.id.tv_sort);
        tvSort.setOnClickListener(this);
        llTitle = findViewById(R.id.ll_title);
        rv = findViewById(R.id.rv);
        srf = findViewById(R.id.srf);
        rlLoading = findViewById(R.id.rl_loading);
        rlContent = findViewById(R.id.rl_content);
        rlLoading.setVisibility(View.VISIBLE);
        sortInfos = new ArrayList<>();
        sortInfos.add(new SortInfo("由高到低", false));
        sortInfos.add(new SortInfo("由低到高", false));
//        sortInfos.add(new SortInfo("默认排序", false));
    }

    /**
     * 初始化下拉刷新
     */
    private void initSfr() {
        SrfManager.setSmartByPullListener(srf, null);
    }


    /**
     * 获取传递的数据
     */
    private void initIntent() {
        userClass = getIntent().getStringExtra("classnum");
        title = getIntent().getStringExtra("title");
        tagid = getIntent().getStringExtra("tagid");
        tvStTitle.setText(title);
    }

    /**
     * 设置里列表
     */
    private void initRv() {

        oldDatas = new ArrayList<>();
        cloneDatas = new ArrayList<>();
        emptyView = View.inflate(this, R.layout.base_rv_common_empty_view, null);
        TextView tvMsg = emptyView.findViewById(R.id.tv_content);
        tvMsg.setText("您还未上传考试成绩");
        adapter = new ScortDetailsGvAapter(this, R.layout.teacher_rv_score_details, oldDatas);
    }

    /**
     * 初始化列表适配器
     */
    private void http(final int method) {
        Map<String, String> map = new HashMap<>();
        map.put("type", "19");
        map.put("acc", AccountUtils.getAccount(this));
        map.put("role", AccountUtils.getRole(this));
        map.put("userClass", userClass + "");
        map.put("tagId", tagid + "");
        map.put("apptoken", AccountUtils.getToken(this));
        map.put("platform", "2");

        HttpUtils.post(HttpAddress.SCORETHEME, map, this, new HttpUtils.CallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                if (rlLoading != null && rlLoading.getVisibility() == View.VISIBLE) {
                    rlLoading.setVisibility(View.GONE);
                }
                UiUtils.Toast(BaseApplication.ERROR, false);
            }

            @Override
            public void onResponse(String response, int id) {
                if (rlLoading != null && rlLoading.getVisibility() == View.VISIBLE) {
                    rlLoading.setVisibility(View.GONE);
                }

                if (rlContent != null && rlContent.getVisibility() != View.VISIBLE) {
                    rlContent.setVisibility(View.VISIBLE);
                }

                Log.i("test", "成绩详情数据：" + response);

                if (!TextUtils.isEmpty(response)) {
                    ScoreDetailsInfo info = null;
                    try {
                        info = GsonUtil.jsonToBean(response, ScoreDetailsInfo.class);
                    } catch (Exception e) {
                        Log.i("test", "数据解析异常");
                    }
                    if (null != info && "200".equals(info.getState())) {

                        //返回成功
                        List<ScoreDetailsInfo.DataBean> newDatas = info.getData();
                        if (newDatas != null) {
                            //设置列表适配器
                            if (newDatas != null) {
                                if (method == BqaManager.NORML) {
                                    oldDatas.clear();
                                    oldDatas.addAll(newDatas);
                                    cloneDatas.clear();
                                    cloneDatas.addAll(newDatas);
                                    GridLayoutManager layoutManager = new GridLayoutManager(TeacherScoreDetailsActivity.this, 3);
                                    BqaManager.setRv(emptyView, layoutManager, TeacherScoreDetailsActivity.this, adapter, rv, null);
                                }
                            }
                        }
                    } else {
                        UiUtils.Toast("返回器返回异常,错误码是:" + info.getState(), false);
                        Log.i("test", "返回器返回异常,错误码是:" + info.getState());
                    }
                } else {
                    Log.i("test", "服务器返回数据为空");
                }
            }
        });
    }

    /**
     * 展示排序的PopUpWindow
     */
    private void showSortPop() {

        View view = View.inflate(getApplicationContext(), R.layout.teacher_pop_sort, null);
        lv = view.findViewById(R.id.lv);
        sortLvAdapter = new SortLvAdapter(TeacherScoreDetailsActivity.this, sortInfos, R.layout.teacher_lv_sort);
        lv.setAdapter(sortLvAdapter);
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int pos, long l) {
                //条目点击事件
                if (pos == 0) {
                    //由高到低
                    doDescAction();
                } else if (pos == 1) {
                    //由低到高
                    deAescAction();
                }
//                else if (pos == 2) {
//                    //默认排序
//                    doDefaultAciton();
//                }
                popupWindow.dismiss();
            }
        });
        popupWindow = new PopupWindow(view, WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT);
        popupWindow.setFocusable(true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupWindow.setAnimationStyle(R.style.common_popwindow_anim_style);
        popupWindow.showAsDropDown(tvSort);
    }


//    /**
//     * 默认排序
//     */
//    private void doDefaultAciton() {
//        oldDatas.clear();
//        oldDatas.addAll(cloneDatas);
//        adapter.notifyDataSetChanged();
//    }


    /**
     * 分数做降序处理
     */
    private void doDescAction() {
        oldDatas.clear();
        oldDatas.addAll(cloneDatas);
        adapter.notifyDataSetChanged();
    }


    /**
     * 分数做升序处理
     */
    private void deAescAction() {
        Collections.reverse(oldDatas);
        adapter.notifyDataSetChanged();
    }


    /**
     * 点击事件
     *
     * @param v
     */
    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.iv_back) {
            //返回
            finish();
        } else if (id == R.id.tv_sort) {
            //排序
            showSortPop();
        } else if (id == R.id.iv_edit) {
            //编辑,修改测试主题
            showUpdatePop();
        }
    }


    /**
     * 修改测试主题的弹框
     */
    private void showUpdatePop() {
        PopUpManager.showPop(this, R.layout.teacher_pop_updatetag, 0.3f, this, new PopUpManager.onGetViewListener() {
            @Override
            public void getChildView(View view, int layoutResId) {
                ImageView ivDelete = view.findViewById(R.id.lv_close);
                Button btCommit = view.findViewById(R.id.bt_commit);
                final EditText etMsg = view.findViewById(R.id.et_message);

                etMsg.setHint("输入新的测试主题");

                etMsg.setFilters(new InputFilter[]{new MaxTextLengthFilter(21)});
                ivDelete.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        PopUpManager.dismiss();
                    }
                });
                btCommit.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        String content = etMsg.getText().toString().trim();
                        if (TextUtils.isEmpty(content)) {
                            UiUtils.Toast("请先输入内容", false);
                            return;
                        } else {
                            //提交服务器
                            doUpdateTagAction(content);
                        }
                    }
                });
            }
        });
    }

    /**
     * 上传服务器修改测试主题
     */
    private void doUpdateTagAction(final String tag) {
        PopUpManager.dismiss();
        CustomDialogManager.show(this, "修改中...");
        Map<String, String> map = new HashMap<>();
        map.put("type", "20");
        map.put("acc", AccountUtils.getAccount(this));
        map.put("role", AccountUtils.getRole(this));
        map.put("tag", tag);
        map.put("rowId", tagid);
        map.put("apptoken", AccountUtils.getToken(this));
        map.put("platform", "2");

        HttpUtils.post(HttpAddress.SCORETHEME, map, this, new HttpUtils.CallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                CustomDialogManager.dissmiss();
                UiUtils.Toast(BaseApplication.ERROR, false);
            }

            @Override
            public void onResponse(String response, int id) {
                CustomDialogManager.dissmiss();
                if (!TextUtils.isEmpty(response)) {
                    ResultInfo info = null;
                    try {
                        info = GsonUtil.jsonToBean(response, ResultInfo.class);
                    } catch (Exception e) {
                        Log.i("test", "数据解析异常");
                    }

                    if (null != info) {
                        if ("200".equals(info.getState())) {
                            //返回成功
                            UiUtils.Toast("测试主题修改成功", false);
                            //更改标题栏的名称
                            tvStTitle.setText(tag);
                            //通知成绩管理界面进行界面刷新
                            BusInfo busInfo = new BusInfo();
                            busInfo.type = TeacherScoreManagerActivity.REFRESHDATA;
                            EventBus.getDefault().post(busInfo);
                        } else {
                            UiUtils.Toast("修改失败,返回错误码:" + info.getState(), false);
                            Log.i("test", "返回器返回异常,错误码是:" + info.getState());
                        }
                    }
                } else {
                    Log.i("test", "服务返回数据异常");
                }
            }
        });
    }

    /**
     * 事件处理
     *
     * @param busInfo
     */
    @Override
    public void busEvent(BusInfo busInfo) {
        super.busEvent(busInfo);
        if (busInfo != null && busInfo.type == UPDATASCORE) {
            //取出rowId和添加的分数
//            int rowId = busInfo.getRowId();
//            String addScore = busInfo.getAddScore();
//            //通过rowId来更新相对应学生的分数,然后适配器刷新
//            for (int i = 0; i < oldDatas.size(); i++) {
//                if (oldDatas.get(i).getROW_ID() == rowId) {
//                    oldDatas.get(i).setSCORE(addScore);
//                }
//            }
//            adapter.notifyDataSetChanged();
            //重新请求服务器
            http(BqaManager.NORML);
        }
    }
}
